﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirtualPress.Portal.WebLogic.Authentication;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Portal.WebLogic;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Portal.Biz;
using VirtualPress.Portal.Web.Areas.WorkSpace.Models;
using System.IO;
using System.Linq.Expressions;
using VirtualPress.Infrastructure.Entities.Repository;
using System.Drawing;
using System.Text;
using VirtualPress.Tool.Framework;

namespace VirtualPress.Portal.Web.Areas.WorkSpace.Controllers
{
#if !DEBUG
    [ErrorHandle]
#endif
    [Auth(UserRole.MagazineAdmin, UserRole.Admin)]
    [WorkSpace(UserRole.MagazineAdmin)]
    public class MagazineController : Controller
    {
        //
        // GET: /WorkSpace/Magazine/

        public ActionResult Index()
        {
            return View();
        }

        #region 征稿中心
        public ActionResult Article(int journal = -1, int group = 0, int page = 0)
        {
            var groupmap = new
            {
                最新 = new List<int>() { 0 },
                专审 = new List<int>() { 110 },
                录用 = new List<int>() { 120 },
            };
            Periodical entity = ViewBag.Journal;
            Expression<Func<T_Article, bool>> where = null;
            if (group == 9)
            {
                where = c => c.Peri_Id == entity.Id && !c.IsDelete;
            }
            else
            {
                List<int> contain = new List<int>();
                switch (group)
                {
                    default:
                    case 0:
                        contain = groupmap.最新;
                        break;
                    case 1:
                        contain = groupmap.专审;
                        break;
                    case 2:
                        contain = groupmap.录用;
                        break;
                }
                where = c => c.Peri_Id == entity.Id && contain.Contains(c.Status) && !c.IsDelete;
            }
            List<Article> list = JournalBiz.GetAllArticle(where, false, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                JournalBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            ViewBag.Group = group;
            ViewBag.Journal = entity;
            return View();
        }
        [SelfArticle("id")]
        public ActionResult ArticleDetail(int id)
        {
            var article = new Article().Find(c => c.Id == id);
            var author = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            //作者信息
            ViewBag.ArticleAuthor = author;
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Journal = journal;
            //附件
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = JournalBiz.GetAllArticleHistory(article.Id);
            //审稿记录
            var records = JournalBiz.GetAllAuditingRecord(article.Id); ;
            ViewBag.AuditingRecord = records;
            var ExpertList = JournalBiz.FindExpertForExamine(journal, article,
                records.Where(c => c.Step != ExamineStep.ChuShen)
                       .Select(c => c.UserName).ToList());
            ViewBag.ExpertList = ExpertList;
            return View();
        }
        public ActionResult MagaZineExamine(int articleId, int result, string msg)
        {
            MagazineBiz.MagazineExamine(articleId, result, msg.NoHTMLLabel("script"));
            return Redirect("/workspace/magazine/article?group=0");

        }
        public ActionResult CancelArticle(int id, int group = 0)
        {
            JournalBiz.CancelArticleForJournal(id);
            return RedirectToAction("Article", new { group = group });
        }
        public ActionResult examinecomplete(int id, int group = 0)
        {
            MagazineBiz.ExamineComplete(id);
            return Redirect("/workspace/magazine/article?group=0");
        }
        public ActionResult IsPublish(int id, int group = 0)
        {
            MagazineBiz.IsPublish(id);
            return Redirect("/workspace/magazine/article?group=0");
        }
        #endregion

        #region 稿件出版
        public ActionResult Publish(int c=0, int page = 0, int journal = -1)
        {
            ViewBag.C = c;
            Periodical entity = ViewBag.Journal;
            List<MagazineItem> data = MagazineBiz.GetAllJournalItem(entity.Id, page, 10);
            ViewBag.Data = new ItemListBox<MagazineItem>(data)
                .BuildPage(MagazineBiz.GetAllJournalItemForPage(entity.Id), page, 10,
                    new PageParameter() { Style = "workspace" });
            return View();
        }
        public ActionResult NewPublish(string t="")
        {
            if (!String.IsNullOrEmpty(t))
            {
                ViewBag.Error = "该期编号已经存在，请查证！";
            }
            return View();
        }
        [HttpPost]
        public ActionResult NewPublish(string Manuscriptcode, string PublishDate, int journal = -1)
        {
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }
            if (entity == null)
            {
                return Redirect(String.Format("/workspace/home/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            if (new MagazineItem().Any(c =>c.PeriodicalId == entity.Id && c.Manuscriptcode == Manuscriptcode))
            {
                return RedirectToAction("NewPublish", new { t = "exist" });
            }
            MagazineBiz.NewJournalItem(entity.Id, Manuscriptcode, PublishDate);
            return RedirectToAction("Publish");
        }
        public ActionResult DeleteJournalItem(int journalItemId, int journal = -1)
        {
            Periodical entity = ViewBag.Journal;
            MagazineBiz.DeleteJournalItem(entity.Id, journalItemId);
            return RedirectToAction("Publish");
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult publishmagazineItem(int journalItemId, string information)
        {
            int success = MagazineBiz.PublishJournalItem(journalItemId,information);
            if (success == -1)
            {
                return RedirectToAction("Publish", new { c="-1"});
            }
            else if (success == 2)
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=publishjournalitem&s=2");
                //因为期刊被禁用
            }
            return RedirectToAction("Publish");
        }
        #endregion

        #region 期刊管理
        public ActionResult BaseInfo(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult BaseInfoEdit(int Id, NewJournalModel model)
        {
            var journal = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journal != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["CoverImg"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = "/content/journal/" + journal.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + journal.Name + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Server.MapPath(filePath));
                    journal.CoverImg = filePath;
                }

                journal.Admin = model.Admin;
                journal.BSGW = model.BSGW;
                journal.BSGW_EN = model.BSGW_EN;
                journal.CallForPaper = model.CallForPaper;
                journal.CallForPaper_EN = model.CallForPaper_EN;
                journal.CBDW = model.CBDW;
                journal.CBDW_EN = model.CBDW_EN;
                journal.Editer_EN = model.Editer_EN;
                journal.Editor = model.Editor;
                journal.Email = model.Email;
                journal.FoundTime = model.FoundTime;
                journal.GJBZLXCBWH = model.GJBZLXCBWH;
                journal.GJGW = model.GJGW;
                journal.GJGW_EN = model.GJGW;
                journal.GNTYLXCBWH = model.GNTYLXCBWH;
                journal.IndType = (Infrastructure.Entities.Enum.Profession)model.IndType;
                //journale.Introduction = model.Introduction;
                //journale.Introduction_EN = model.Introduction_EN;
                journal.ISSN_Online = model.ISSN_Online;
                journal.ISSN_Print = model.ISSN_Print;
                journal.Name = model.Name;
                journal.Name_EN = model.Name_EN;
                journal.Press_Id = model.Press_Id;
                journal.PubRate = (PubRate)model.PubRate;
                journal.PubTime = model.PubTime;
                journal.Range = model.Range;
                journal.RegTime = model.RegTime;
                //journale.Retrieval = model.Retrieval;
                journal.XBDW = model.XBDW;
                journal.XBDW_EN = model.XBDW_EN;
                journal.YFDH = model.YFDH;
                journal.ZBDW = model.ZBDW;
                journal.ZBDW_EN = model.ZBDW_EN;
                journal.ZCDW = model.ZCDW;
                journal.ZCDW_EN = model.ZCDW_EN;
                journal.ZGDW = model.ZGDW;
                journal.ZGDW_EN = model.ZGDW_EN;

                if (journal.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=baseinfoedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=baseinfoedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Introduction(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult IntrodutionEdit(int Id, string Introduction, string Introduction_EN)
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.Introduction = Introduction.NoHTMLLabel("script");
                journale.Introduction_EN = Introduction_EN.NoHTMLLabel("script");
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=introdutionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=introdutionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Announcement(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AnnouncementEdit(int Id, string Announcement, string Announcement_EN = "")
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.CallForPaper = Announcement.NoHTMLLabel("script");
                //journale.CallForPaper_EN = Announcement_EN;
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=announcementedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=announcementedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Attention(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AttentionEdit(int Id, string Attention)
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.Attention = Attention.NoHTMLLabel("script");
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=attentionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=attentionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Links(int journal = -1, int page = 0)
        {
            Periodical entity = ViewBag.Journal;
            var list = new ItemListBox<FriendLink>(JournalBiz.GetAllLinks(c => c.RelationId == entity.Id && c.RelationType==1, page, 20));
            list.BuildPage(JournalBiz.GetAllLinksForPage(c => c.RelationId == entity.Id && c.RelationType == 1),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.Links = list;
            return View();
        }
        public ActionResult AddLinks(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddLinks(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink item = JournalBiz.SaveNewFriendLink(new FriendLink()
            {
                CreateTime = DateTime.Now,
                RelationId = Id,
                RelationType=1,
                Remark = Remark,
                Title = Title,
                URL = URL
            });
            if (item != null)
            {
                return Redirect("/workSpace/magazine/links");
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=addlinks&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult LinkEdit(int Id, int journal = -1)
        {
            FriendLink item = JournalBiz.GetLink(Id);
            ViewBag.Link = item;
            return View();
        }
        [HttpPost]
        public ActionResult LinkEdit(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink data = JournalBiz.GetLink(Id);
            if (data != null)
            {
                data.Title = Title;
                data.URL = URL;
                data.Remark = Remark;
                if (data.PostModify() != null)
                {
                    return Redirect("/workSpace/magazine/links");
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=linkedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult LinkCancel(int Id, int journal = -1)
        {
            FriendLink link = new FriendLink().Find(Id.ToString());// JournalBiz.GetLink(Id);
            if (link != null)
            {
                link.PostDelete();
            }
            return Redirect(String.Format("/WorkSpace/magazine/Links{0}", journal >= 0 ? "?journal=" + journal : ""));
        }
        public ActionResult Settings(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult Settings(string ZGFW, int journal = -1)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }
            entity.ZGFW = ZGFW;
            if (entity.PostModify() != null)
            {
                return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=settings&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + journal : ""));
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=magazine&a=settings&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + journal : ""));
        }
        #endregion
    }
}
